<?php
/**
 * 行为日志记录
 */
class ActionAction extends CommonAction {

         
	//过滤查询字段
	function _filter(&$map){
		$key = trim($_REQUEST['keywords']);
        if(strpos($key, ' ')){ //高级搜索，仅搜索产品名称

            $map = A('Search')->search($key,'Action','comment');
        }else if(!empty($key)) {
            $map['comment'] = array('like',"%".$key."%");//产品名称
            $map['obj_id'] = array('like',"%".$key."%");//销售单号
            $map['model'] = array('like',"%".$key."%");//条码
            /* exact filter
            $map['Warehouse.name'] = array('like',"%".$key."%");//仓库
            $map['Customer.name'] = array('like',"%".$key."%");//customer
            $map['number'] = array('eq',$key);
            //$map['minstock'] = array('like',"%".$key."%");*/
            $map['_logic'] = "or";
        }
                
	}

        public function  _before_edit() {
            //TODO 需加field字段对应名称配置表
            $history = array();
            $history = M('History')->where('action_id ='.$_REQUEST['id'])->findAll();
            $this->assign('historys', $history);
    }

	/** only recove deleted history
    * @param array action:need to recover action record
    *
    **/
    public function recover_delete($action_id,$model)
    {
        $action_id = empty($_REQUEST['action_id']) ? $action_id : $_REQUEST['action_id'];
        $model = empty($_REQUEST['model']) ? $model : $_REQUEST['model'];
        if(empty($action_id) || empty($model) )
            $this->error('参数传递错误');

        $deletes = M('History')->where('action_id = '.$action_id.' and field="delete"')->find();
        $diff = unserialize($deletes['diff']);
        $error_msg = "恢复失败：";
        $succ_msg = "成功恢复:";
        foreach ($diff as $key => $value) {
            $id = M($model)->add($value);
            if(!$id)
                $error_msg .= $value['id'].',';
            else
                $succ_msg .= $id.',';
        }
        $this->success($succ_msg.';<br/> '.$error_msg,false,20);
    }

        /**
         * 记录日志,如果是add操作，则勿需传入old,new
         * @param <string> $message 备注说明或概述
         * @param <string> $action 操作 ：新建，删除，修改，登入，登出
         * @param <string> $model 记录的模型
         * @param <int> $obj_id 变动对象ID号
         * @param <array> $old 老数据对象
         * @param <array> $new 新数据对象
         */
        public function writeLog($message,$action,$model,$obj_id=0,$old='',$new=''){
            if($this->is_blocked($model) )
                return; //如果是非日志记录类,则停止记录
            $action_id = $this->insertAction($message, $action, $model,$obj_id);
            $changes = '';
            $common = D('Common');
            if(is_array($old) && is_array($new)){
                if($action == '删除')
                    $changes['0'] = array(
                        'action_id' => $action_id,
                        'field' => 'delete',
                        'old' =>1,
                        'new' =>0,
                        'diff' => serialize ($old),
                    );
                else
                    $changes = D('Common')->createChanges($old,$new);  //$common::createChanges($old,$new); //php5.3+
            }
            D('Action')->logHistory($action_id,$changes);

        }

        /**
         * 记录日志
         * @param <string> $message 备注说明或概述
         * @param <string> $action 操作 ：新建，删除，修改，登入，登出
         * @param <string> $model 记录的模型
         * * @param <int> $obj_id 变动对象ID号
         */
        public function insertAction($message,$action,$model,$obj_id){
            $data = array(
                'comment' => $message,
                'model' => $model,
                'action' => $action,
                'obj_id' => $obj_id,
                'ip' => get_client_ip(),
                'user_id' => $_SESSION[C('USER_AUTH_KEY')],
                'create_time' => time()
            );
            $action_id = M('Action')->add($data);
            return $action_id;

        }

         /**
     * Print changes of every action.
     *
     * @param  string    $objectType model
     * @param  array     $histories
     * @access public
     * @return void
     */
    public function printChanges($objectType,$histories)
    {

        $diff1        = '修改了 <strong><i>%s</i></strong>，旧值为 "%s"，新值为 "%s"。<br />';
         $diff2        = '修改了 <strong><i>%s</i></strong>，区别为:<blockquote>%s</blockquote>';

        if(empty($histories)) return;

        $maxLength            = 0;          // The max length of fields names.
        $historiesWithDiff    = array();    // To save histories without diff info.
        $historiesWithoutDiff = array();    // To save histories with diff info.

        /* Diff histories by hasing diff info or not. Thus we can to make sure the field with diff show at last. */
        foreach($histories as $history)
        {
            $fieldName = $history['field'];
            //TODO 做字段映射
            //$history->fieldLabel = isset($this->lang->$objectType->$fieldName) ? $this->lang->$objectType->$fieldName : $fieldName;
            $history['fieldLabel'] = $fieldName;
            //if(($length = strlen($history->fieldLabel)) > $maxLength) $maxLength = $length;
            if(($length = strlen($fieldName)) > $maxLength) $maxLength = $length;
            $history['diff'] ? $historiesWithDiff[] = $history : $historiesWithoutDiff[] = $history;
        }
        $histories = array_merge($historiesWithoutDiff, $historiesWithDiff);

        foreach($histories as $history)
        {
            //$history['fieldLabel'] = str_pad($history['fieldLabel'], $maxLength, $this->lang->action->label->space);
            if($history['diff'] != '')
            {
                $history['diff'] = str_replace(array('<ins>', '</ins>', '<del>', '</del>'), array('[ins]', '[/ins]', '[del]', '[/del]'), $history['diff']);
                $history['diff'] = $history['field'] != 'subversion' ? htmlspecialchars($history['diff']) : $history['diff'];   // Keep the diff link.
                $history['diff'] = str_replace(array('[ins]', '[/ins]', '[del]', '[/del]'), array('<ins>', '</ins>', '<del>', '</del>'), $history['diff']);
                $history['diff'] = nl2br($history['diff']);
                printf($diff2, $history['field'], $history['diff']);
            }
            else
            {
                printf($diff1, $history['fieldLabel'], $history['old'], $history['new']);
            }
        }
    }
	
    /**block list,if these model,then no log
    **@model model name
    **/
    public function is_blocked($model='')
    {
        $block_model = 'product_map,configure,logicompany,brand,category,customer,reconcile,node,group,operation_log,message,customer,shipping_address,crontab';
        if(false !== strpos($block_model, strtolower($model)) )
            return true;
        return false;
    }
	
}
?>
